package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-07
 */
@Service
@Slf4j
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private IElderService elderService;
    @Autowired
    private ICheckInConfigService checkInConfigService;
    @Autowired
    private IBedService bedService;
    @Autowired
    private IContractService contractService;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1.检验老人是否已入住
        //查询老人select * from elder where id_cardNo = ?
        Elder elder = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                .one();
        if (elder != null) {
           throw new RuntimeException("该老人信息已存在");
        }
        //2.更新床位状态
        Bed bed = new Bed();
        bed.setId(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedService.updateBed(bed);
        //3.新增或更新老人
        Elder beanElder = BeanUtil.toBean(checkInApplyDto.getCheckInElderDto(), Elder.class);
        beanElder.setStatus(1);
        beanElder.setBedId(checkInApplyDto.getCheckInConfigDto().getBedId());
        //床位编号
        bed = bedService.lambdaQuery()
                .eq(Bed::getId, checkInApplyDto.getCheckInConfigDto().getBedId())
                .one();
        beanElder.setBedNumber(bed.getBedNumber());
        elderService.saveOrUpdate(beanElder);
        //4.新增签约办理
        Contract contract = BeanUtil.toBean(checkInApplyDto.getCheckInContractDto(), Contract.class);
        contract.setElderId(beanElder.getId());
        contract.setContractNumber("htu"+ CodeGenerator.generateContractNumber());
        contract.setElderName(beanElder.getName());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        if (contract.getStartDate().isAfter(LocalDateTime.now())){
            contract.setStatus(1);
        }else {
            contract.setStatus(0);
        }
        contractService.save(contract);
        //5.新增入住信息
        CheckIn checkIn = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderId(beanElder.getId());
        checkIn.setElderName(beanElder.getName());
        checkIn.setIdCardNo(beanElder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        if (checkIn.getStartDate().isAfter(LocalDateTime.now())){
            checkIn.setStatus(1);
        }else {
            checkIn.setStatus(0);
        }
        //将家人信息转为json字符串
        checkIn.setRemark(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));
        this.save(checkIn);
        //6.新增入住配置
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigService.save(checkInConfig);
    }

    @Override
    public CheckInDetailVo selectCheckInDetailById(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //1.查询入住信息
        CheckIn checkIn = lambdaQuery().eq(CheckIn::getId, id).one();

        //2.查询入住配置
        CheckInConfig checkInConfig = checkInConfigService.lambdaQuery()
                .eq(CheckInConfig::getCheckInId, checkIn.getId())
                .one();
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //3.查询入住老人
        Elder elder = elderService.lambdaQuery()
                .eq(Elder::getId, checkIn.getElderId())
                .one();
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
        //根据生日算出年龄
        checkInElderVo.setAge(DateUtil.ageOfNow(elder.getBirthday()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //4.查询入住老人关系
        // 将json字符串转为对象
        String remark = checkIn.getRemark();
        log.info("remark:{}", remark);
        List<ElderFamilyVo> elderFamilyList = JSONUtil.toList(remark, ElderFamilyVo.class);
        log.info("elderFamilyList:{}", elderFamilyList);
        checkInDetailVo.setElderFamilyVoList(elderFamilyList);
        //5.查询签约办理
        Contract contract = contractService.lambdaQuery()
                .eq(Contract::getElderId, elder.getId())
                .one();
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}
